package com.edu.controller;

import com.edu.beans.Home;
import com.edu.exception.UsedException;
import com.edu.service.HomeService;
import com.edu.service.impl.HomeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@WebServlet("/HomeServlet.do")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2,  // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50    // 50MB
)
public class HomeServlet extends HttpServlet {

    HomeService homeService = new HomeServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        // 获取请求参数中的 action 字段
        String action = req.getParameter("action");
        switch (action) {
            case "queryHome":
                queryHome(req, resp);
                break;
            case "addHome":
                addHome(req, resp);
                break;
            case "goUpdateHome":
                goUpdateHome(req, resp);
                break;
            case "updateHome":
                updateHome(req, resp);
                break;
            case "showHome":
                showHomeM(req, resp);
                break;
            case "deleteHome":
                deleteHome(req, resp);
                break;
            case "goUpdateHomeState":
                goUpdateHomeState(req, resp);
                break;
            case "updateHomeState":
                updateHomeState(req, resp);
                break;
            default:
                // 如果 action 不匹配，返回错误信息
                resp.getWriter().write("<script>alert('未知操作');window.location.href='/views/index.jsp';</script>");
                break;
        }
    }

    /**
     * 更新房屋状态
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException
     */
    private void updateHomeState(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String state = req.getParameter("state");
        Home home=homeService.getHomeById(Integer.parseInt(id));
        home.setState(state);
        int count = homeService.updateHome(home);
        if (count > 0) {
            resp.getWriter().write("<script>alert('房屋状态更新成功');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        } else {
            resp.getWriter().write("<script>alert('房屋状态更新失败');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        }
    }

    /**
     * 跳转到更新房屋状态页面
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws ServletException
     * @throws IOException
     */
    private void goUpdateHomeState(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Home home = homeService.getHomeById(Integer.parseInt(id));
        if (home != null) {
            req.setAttribute("home", home);
            req.getRequestDispatcher("/views/H_Type_update.jsp").forward(req, resp);
        }
    }

    /**
     * 删除房屋信息
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException
     */
    private void deleteHome(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String id = req.getParameter("id");
            int count = homeService.deleteHomeById(Integer.parseInt(id));
            if (count > 0) {
                resp.getWriter().write("<script>alert('房屋信息删除成功');window.location.href='/HomeServlet.do?action=queryHome';</script>");
            } else {
                resp.getWriter().write("<script>alert('房屋信息删除失败');window.location.href='/HomeServlet.do?action=queryHome';</script>");
            }
        } catch (UsedException e) {
            resp.getWriter().write("<script>alert('"+e.getMessage()+"');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        }
    }

    /**
     * 显示房屋信息
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException
     */
    private void showHomeM(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Home home = homeService.getHomeById(Integer.parseInt(id));
        if (home != null) {
            req.setAttribute("home", home);
            req.getRequestDispatcher("/views/home_show.jsp").forward(req, resp);
        } else {
            resp.getWriter().write("<script>alert('房屋信息不存在');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        }
    }

    /**
     * 更新房屋信息
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException
     * @throws ServletException
     */
    private void updateHome(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Collection<Part> parts = req.getParts();
        String img=req.getParameter("img");
        for (Part part : parts) {
            if (part.getSubmittedFileName() != null && !part.getSubmittedFileName().isEmpty()) {
                // 获取文件名
                img = UUID.randomUUID().toString() + "." + part.getSubmittedFileName().split("\\.")[1];
                String filePath = req.getServletContext().getRealPath("upload") + "/" + img;
                // 保存文件到服务器
                part.write(filePath);
                img= "/upload/" + img; // 更新img路径
                System.out.println("文件上传成功，文件上传的路径:" + filePath);
            }
        }
        String id = req.getParameter("id");
        Home home = homeService.getHomeById(Integer.parseInt(id));
        home.setImg(img);
        home.setNum(Integer.parseInt(req.getParameter("num")));
        home.setH_type(req.getParameter("h_type"));
        home.setPrice(req.getParameter("price"));
        home.setState(req.getParameter("state"));
        home.setText(req.getParameter("text"));
        int count = homeService.updateHome(home);
        if (count > 0) {
            resp.getWriter().write("<script>alert('房屋信息修改成功');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        } else {
            resp.getWriter().write("<script>alert('房屋信息修改失败');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        }
    }

    /**
     * 跳转到更新房屋信息页面
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws ServletException
     * @throws IOException
     */
    private void goUpdateHome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Home home = homeService.getHomeById(Integer.parseInt(id));
        if (home != null) {
            req.setAttribute("home", home);
            req.getRequestDispatcher("/views/home_update.jsp").forward(req, resp);
        } else {
            resp.getWriter().write("<script>alert('房屋信息不存在');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        }
    }

    /**
     * 添加房屋信息
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws IOException
     * @throws ServletException
     */
    private void addHome(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Collection<Part> parts = req.getParts();
        String fname = "";
        for (Part part : parts) {
            if (part.getSubmittedFileName() != null && !part.getSubmittedFileName().isEmpty()) {
                // 获取文件名
                fname = UUID.randomUUID().toString() + "." + part.getSubmittedFileName().split("\\.")[1];
                String filePath = req.getServletContext().getRealPath("upload") + "/" + fname;
                // 保存文件到服务器
                part.write(filePath);
                System.out.println("文件上传成功，文件上传的路径:" + filePath);
            }
        }
        String num = req.getParameter("num");
        String h_type = req.getParameter("h_type");
        String price = req.getParameter("price");
        String state = req.getParameter("state");
        String img = "/upload/" + fname;
        String text = req.getParameter("text");
        Home home = new Home(Integer.parseInt(num), h_type, price, state, img, text);
        int count = homeService.addHome(home);
        if (count > 0) {
            resp.getWriter().write("<script>alert('房屋信息添加成功');window.location.href='/HomeServlet.do?action=queryHome';</script>");
        } else {
            resp.getWriter().write("<script>alert('房屋信息添加失败');window.location.href='/views/home_add.jsp';</script>");
        }
    }

    /**
     * 获取房屋信息
     *
     * @param req  请求对象
     * @param resp 响应对象
     * @throws ServletException
     * @throws IOException
     */
    private void queryHome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String num = req.getParameter("num");
        if (num == null) {
            num = "";
        }
        List<Home> allHomeByNum = homeService.getAllHomeByNum(num);
        req.setAttribute("allHomeByNum", allHomeByNum);
        req.getRequestDispatcher("/views/home_list.jsp").forward(req, resp);
    }

}
